// 类型定义
interface CookieOptions {
  expires?: number | Date;
  path?: string;
  domain?: string;
  secure?: boolean;
  sameSite?: "strict" | "lax" | "none";
}

// 原生实现
export const cookie = {
  set(name: string, value: string, options?: CookieOptions): void {
    let cookieString = `${encodeURIComponent(name)}=${encodeURIComponent(
      value
    )}`;

    if (options) {
      if (options.expires) {
        const expires =
          options.expires instanceof Date
            ? options.expires
            : new Date(Date.now() + options.expires * 864e5);
        cookieString += `; expires=${expires.toUTCString()}`;
      }
      if (options.path) cookieString += `; path=${options.path}`;
      if (options.domain) cookieString += `; domain=${options.domain}`;
      if (options.secure) cookieString += "; secure";
      if (options.sameSite) cookieString += `; samesite=${options.sameSite}`;
    }

    document.cookie = cookieString;
  },

  get(name: string): string | null {
    const cookies = document.cookie.split(";");
    for (const cookie of cookies) {
      const [cookieName, cookieValue] = cookie.trim().split("=");
      if (decodeURIComponent(cookieName) === name) {
        return decodeURIComponent(cookieValue);
      }
    }
    return null;
  },

  remove(name: string, path?: string): void {
    this.set(name, "", { expires: -1, path });
  },
};
